package com.example.friend.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.domain.R;
import com.example.common.core.domain.ResultCode;
import com.example.common.core.domain.TableDataInfo;
import com.example.friend.domain.question.question.Question;
import com.example.friend.domain.question.question.dto.QuestionAddDTO;
import com.example.friend.domain.question.question.dto.QuestionEditDTO;
import com.example.friend.domain.question.question.dto.QuestionQueryDTO;
import com.example.friend.domain.question.question.vo.QuestionDetailVo;
import com.example.friend.domain.question.question.vo.QuestionVO;
import com.example.friend.mapper.question.QuestionMapper;
import com.example.friend.service.IQuestionService;
import com.example.security.exception.ServiceException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class QuestionService implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    /**
     * @param questionQueryDTO
     * @return
     */
    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
        List<QuestionVO> questionVOList = questionMapper.selectQuestionList(questionQueryDTO);
        if (questionVOList == null || questionVOList.isEmpty()) {
            return TableDataInfo.empty();
        }
        log.info("com.example.service-questionVOList{}", questionVOList);
        return TableDataInfo.success(questionVOList, new PageInfo<>(questionVOList).getTotal());
    }


    @Override
    public QuestionDetailVo getQuestionDetailById(Long questionId) {
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .ne(Question::getDeleteFlag, 0).eq(Question::getQuestionId, questionId));
        if (questions == null) {
            //question不能为空
            throw new ServiceException(ResultCode.FAILED_GET_QUESTION);
        } else if (questions.size() != 1) {
            //一个questionId只能对应一条数据 查出多条 显然是不合理的
            throw new ServiceException(ResultCode.FAILED_GET_QUESTION);
        }
        log.info("com.example.service-getQuestionDetailById:{}", questions.get(0));
        QuestionDetailVo questionDetailVo = new QuestionDetailVo();
        BeanUtil.copyProperties(questions.get(0), questionDetailVo);
        log.info("com.example.service-getQuestionDetailById:{}", questionDetailVo);
        return questionDetailVo;
    }
}
